import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import store from '@/store'
import { Message } from 'element-ui';
import router from '@/router'
import {dispatch} from '@/api/limits'
import {asyncRoutese} from '@/router/index'

let aa = []
for(let i = 0; i<asyncRoutese[0].children.length;i++){
  aa.push(`/home/${asyncRoutese[0].children[i].path}`)

// const whiteList = ['/','/cms','/404','/home/particulars','/home/snippets','/home/snipngd','/home/imagetext',
//  '/home/addarticle','/home/defract','/home/addClassic','/home/addclass','/home/customization','/home/message','/home/withdraw','/home/elessent','/home/enter',
//  '/home/addindex']

}
var whiteList = ['/','/cms','/404']
// 白名单数组
for (let i = 0; i < aa.length; i++) {
	whiteList.push(aa[i])
}

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  if (whiteList.includes(to.path)){
    next();
    return;
  }
  const token = store.state.token
  // console.log(store);
  const res = await dispatch()
  const menus = res.code
  if(menus != '200'){
    Message.warning('请先登录')
      next('/')
      NProgress.done();
      return;
  }
  if (token) {
    // console.log(menus);
    // const filterRoutes = asyncRoutes.filter(item => menus.includes(item.name))
    // filterRoutes.push({ path: '*', hidden: true })
    // router.addRoutes(filterRoutes)
    // store.commit('menu', filterRoutes)

    // 先看一下当前的路径
    if (!res.data || res.data.length == 0){
      Message.error('没有权限')
      next('/404');
      return;
    }
    if (!to.path){
      Message.error('没有权限')
      next('/404');
      return;
    }
    const path = to.path.substring(to.path.lastIndexOf('/') + 1);
    if(!path){
      Message.error('没有权限')
      next('/404');
      return;
    }
    if (res.data.filter(p=>p.routerPath && p.routerPath == path).length ==0){
      Message.error('没有权限')
      next('/404');
      return;
    }
      next()
  } else { 
    // 没有token，只能访问白名单
    if (whiteList.includes(to.path)) {
      next()
    } else {
      Message.warning('请先登录')
      next('/') 
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
